<?php

namespace app\controller\wmapi\examineapprove;

use app\controller\wmapi\IndexController;
use app\controller\wmapi\message\MessageNotifyController;
use app\controller\wmapi\order\OrderController;
use app\controller\wmapi\PublicCommentController;
use app\model\WaChannel;
use app\model\WaOrders;
use app\model\WaOrdersPurchaseContract;
use app\model\WaSalesOrdersExamineApprove;
use app\model\WaSalesOrdersExamineApproveFlow;
use Illuminate\Support\Facades;
use Illuminate\Support\Facades\Validator;
use plugin\admin\app\common\Util;
use plugin\admin\app\model\Admin;
use support\Request;
use app\model\WaAdmins;
use app\model\WaRoles;
use app\model\WaMembers;
use app\model\WaRules;
use app\model\WaDepartment;
use app\model\WaAdminRoles;
use Illuminate\Support\Facades\DB;
use Tymon\JWTAuth\Facades\JWTAuth;
use Illuminate\Support\Facades\Cache;
use Tinywan\Validate\Validate;
use function Termwind\ValueObjects\p;

class SalesOrdersApproveController extends Validate
{

    /**
     * 销售订单审批 -列表-分页
     * @param Request $request
     * @return mixed
     */
    public function salesOrdersApproveList(Request $request)
    {
        $param = $request->all();
        // 获取管理员信息
        $adminId = json_decode(adminId($request));
        // 获取的是 销售审批id  因为记录不删 合同编号会存在重复
//        $purchasecontractsn = WaSalesOrdersExamineApproveFlow::allIn($adminId);
////        $purchasecontractsn = json_decode($purchasecontractsn);
////        if (!$purchasecontractsn) {
////            $purchasecontractsn = [];
////        }
        $purchasecontractsn = [];

        $fields = ['*'];
        $condition = [];
        $between = [];
        $whereNotIn = [3];
        if ($param['sales_order_sn']) {
            $condition [] = ['sales_order_sn', 'like', '%' . $param['sales_order_sn'] . '%'];
        }

        if ($param['initiator_admin_name']) {
            $condition [] = ['initiator_admin_name', 'like', '%' . $param['initiator_admin_name'] . '%'];
        }

        if ($param['status']) {
            if ($param['status'] == 4){
                $condition [] = ['status', '!=', 3];
            }else{
                $condition [] = ['status', '=', $param['status']];
            }
        }else{
            if ($param['status'] == 0){
                $condition [] = ['status', '=', $param['status']];
            }else{
                $condition [] = ['status', '!=', 3];
            }
        }

        if ($param['start_time'] && $param['end_time']) {
            $between [] = [$param['start_time'], $param['end_time']];
        }
        $page = page($param['page']);
        $pageNum = pageNum($param['pageNum']);
        $rule = WaSalesOrdersExamineApprove::list($param,$adminId, $page, $pageNum,$whereNotIn, $purchasecontractsn, $fields, $condition, $between);

        return IndexController::successed($rule, '销售订单列表');
    }

    /**
     * 销售订单待审批 - 审批人 - 列表
     * 不分页 限制10条
     * @param Request $request
     * @return \support\Response
     */
    public function salesOrdersWaitApproveByAdminIdList(Request $request)
    {
        $param = $request->all();
        // 获取管理员信息
        $adminId = json_decode(adminId($request));
        $purchasecontractsn = [];
        // 获取的是 销售审批id  因为记录不删 合同编号会存在重复
        $purchasecontractsn = WaSalesOrdersExamineApproveFlow::allIn($adminId);
//        $purchasecontractsn = json_decode($purchasecontractsn);
//        if (!$purchasecontractsn) {
//            $purchasecontractsn = [];
//        }
        PublicCommentController::销售订单审批状态;
        $fields = ['*'];
        $condition = [];
        $between = [];

        $page = page($param['page']);
        $pageNum = pageNum($param['pageNum']);
        $rule = WaSalesOrdersExamineApprove::waitApproveByAdminIdList($adminId, $page, $pageNum, $purchasecontractsn, $fields, $condition, $between);

        return IndexController::successed($rule, '销售订单待审批 - 审批人 列表');
    }


    /**
     * 销售订单审批-状态更新
     * @param Request $request
     * @return \support\Response
     */
    public function salesOrdersApproveUpdate(Request $request)
    {
//        process($request);
        $param = $request->all();
        $adminId = json_decode(adminId($request));
        if (array_key_exists('refuse_reason',$param)){
            $refuse_reason = $param['refuse_reason'];
        }else{
            $refuse_reason = '';
        }

        // 当前销售订单审批数据
        $approves = WaSalesOrdersExamineApprove::find(['id' => $param['id']], $adminId);
        $approves = json_decode($approves);
        if (!$approves) {
            return IndexController::errored('', '找不到该销售订单');
        }
        $flow = [];// 当前审批流
        $flow_next = []; // 下级审批流
        // 当前订单审批流
        $flows = WaSalesOrdersExamineApprove::find(['id' => $param['id']], $adminId);
        $flows = json_decode($flows);
        if (!$flows) {
            return IndexController::errored('', '未获取销售订单的审批流');
        }
        // 获取合同中的审批流设置
        $flows->approve_flow = json_decode($flows->approve_flow);

        /**
         * 判断当前合同 当前部门是否审批过  审批中的  sale_no 是 唯一值（审批流中 也要筛选出该编号对应的 审批流 其它的都是作废的）
         * 审核状态 0 待审核 1审批通过 2 审批驳回  3 作废 4  删除
         * 只有轮到的人才有审批的权限 重点
         */
        $condition_flow = [];
        $condition_flow [] = ['sale_no', '=', $approves->sale_no];
        $condition_flow [] = ['status', '=', 0];
        $approve_flow = WaSalesOrdersExamineApproveFlow::find($condition_flow);
        $approve_flow = json_decode($approve_flow);
        if (!$approve_flow) {
            return IndexController::errored('', '找不到该审批的待审批记录');
        }else{
            if (!in_array($adminId->id, json_decode($approve_flow->admin_ids))){
                return IndexController::errored('', '当前审批你没有审批权限');
            }

            foreach ($flows->approve_flow as $k) {
                //获取合同中该用户部门的 审批流
                if ($approve_flow->admin_ids ==  json_encode($k->approve_admin_id)) {
                    $flow = $k;
                }
            }

            if (!$flow) {
                return IndexController::errored('ErrorApproveSetting', '当前用户所在部门未设置审批流程，无法提交审批');
            }


        }

        \support\Db::beginTransaction();
        try {
            if ($param['status'] == 0) {
                return IndexController::errored('', '审批只有通过和驳回和撤回状态哦');
            } elseif ($param['status'] == 1) {
                // 审批通过 判断审批流是否走到最后一步 -> 如果是则多一步创建销售订单   =》 都需要 添加销售订单审批详情记录
                if ($approves) {
                    // 首先这合同必须是审批中的状态
                    if ($approves->status != 0) {
                        return IndexController::errored('', '订单不是待审批状态无法审批');
                    }
                    // 需要判断主订单是否是审批中的状态
                    if ($approves->approve_flow) {


//                    foreach (json_decode($approves->approve_flow) as $k){
                        // 然后判断 当前部门是否审批过 循环所有 审批流的所有部门 正常是按正序循环 找出上级部门为 0 的部门
                        //先查找是否有审批记录 按流程每一个审批操作会自动创建下一个 一条审批或待审批数据
                        $data = [];
                        $data [] = ['check_id', '=', $param['id']];
                        $data [] = ['status', '=', 0];
                        $check_parent = WaSalesOrdersExamineApproveFlow::find($data);
                        $check_parent = json_encode($check_parent);
                        // 只有查到待审批数据的部门才有审批权限
                        if ($check_parent) {
                            $approve_log_condition = [];
                            $approve_log_condition [] = ['sale_no', '=', $approves->sale_no];
                            $approve_log_condition [] = ['status', '=', 0];
                            $approve_log_condition [] = ['admin_ids', '=', $approve_flow->admin_ids];
                            // 添加销售订单审批详情记录
                            $approve_log_data = [
                                'updated_at' => dateTime(),
                                'admin_id' => $adminId->id,
                                'admin_name' => $adminId->nickname,
                                'refuse_reason' => $refuse_reason,
                                'status' => 1, //0 待审批 1审批通过 2 审批驳回
                            ];

                            $add_log = WaSalesOrdersExamineApproveFlow::updated($approve_log_condition, $approve_log_data); // 添加销售订单审批详情记录
                            if (!$add_log) {
                                return IndexController::errored('', '审批流添加错误');
                            }
                            // 判断审批流到哪一步 如果结束则 修改合同状态 创建合同
                            //判断是否是最后一级审批
                            if ($flow->next_sort == 0) {
                                // 最后一级审批  则修改合同审批状态  创建合同
                                // 由销售单创建的销售订单 状态修改
                                if ($approves->sales_order_sn) {
                                    //销售订单状态
                                    PublicCommentController::销售订单状态;
                                    $up_purchase_status = WaOrders::updated(['status' => 17,'updated_at' => dateTime()], ['order_sn' => $approves->sales_order_sn]);// 修改销售订单状态
                                    // 手动创建的销售订单
                                    $up_purchase_approve_status = WaSalesOrdersExamineApprove::updated(['id' => $param['id']], ['status' => 1]); // 修改销售订单审批单状态
                                }
                                // 修改销售订单状态为代付车款  请款单需要手动创建不能自动创建
                                $time = date('H:i:s', time());
                                if ($flows->approve_flow_send_after){
                                    $admin_ids = $flows->approve_flow_send_after;
                                    // 钉钉消息通知 -销订完批通知 抄送
                                    $admin_ids = json_decode($admin_ids);
                                    if ($admin_ids){
                                        foreach ($admin_ids as $kadmin){
                                            $admin_condition = [];
                                            $admin_condition [] = ['id','=',$kadmin];
                                            $admin_data = WaAdmins::find($admin_condition);
                                            if ($admin_data){
                                                $admin_data = json_decode($admin_data);
                                                $data = [
                                                    'mobile' => $admin_data->mobile,
                                                    'title' => '销订完批通知', // 标题
                                                    'markdown' => '销售订单'.$approves->sales_order_sn.'审批已完成'.$time, // 内容
                                                ];
                                                $currentRoute  = $request->host();

                                                // 消息通知
                                                if ( $currentRoute == 'frontforeign.olivenev.com'){
                                                    $message =  MessageNotifyController::dingDingWorkNotify($data, $adminId);
                                                }
                                            }

                                        }

                                    }
                                }



                            }
                            else {
                                $next_sort = $flow->next_sort; //下一级部门
                                foreach ($flows->approve_flow as $k) {
                                    //获取合同中该用户部门的 审批流
                                    if ($k->sort == $next_sort) {
                                        $flow_next = $k;
                                    }

                                }
                                if ($flow_next) {
                                    // 创建下一级待审批流程
                                    $admin_name ='';
                                    if ($flow_next->approve_admin_id){
                                        foreach ($flow_next->approve_admin_id as $apadid) {
                                            $admins = WaAdmins::find(['id' => $apadid]);
                                            $admins = json_decode($admins);
                                            if ($admins) {
                                                $admin_name = $admin_name .'/'. $admins->nickname;
                                            }
                                        }

                                    }
                                     // 添加销售订单审批详情记录
                                    $approve_log_data = [
                                        'sale_no' => $approves->sale_no, // 销售订单编号
                                        'check_id' => $approves->id, // 审批id
                                        'created_at' => dateTime(),
                                        'admin_id' => $adminId->id,
                                        'admin_ids' => json_encode($flow_next->approve_admin_id), //
                                        'admin_name' => $admin_name,
                                        'status' => 0, //0 待审批 1审批通过 2 审批驳回
                                        'sort' => $flow_next->sort, //0 待审批 1审批通过 2 审批驳回
                                    ];
                                    if ($approves->sales_order_sn) {
                                        $approve_log_data['sales_order_sn'] = $approves->sales_order_sn;// 销售订单编号
                                    }
                                    $add_log = WaSalesOrdersExamineApproveFlow::create($approve_log_data); // 添加销售订单审批详情记录
                                    if (!$add_log) {
                                        $data_error = [
                                            '错误：审批流日志添加失败',
                                            '日志信息：'.$add_log,
                                        ];
                                        IndexController::logErrorNew('salesOrdersApproveUpdate', $data_error);
                                        return IndexController::errored('', '审批流日志添加失败');
                                    }
                                    $time = date('H:i:s', time());
                                    $admin_ids = $flow_next->approve_admin_id;
                                    // 钉钉消息通知
                                    if ($admin_ids){

                                        foreach ($admin_ids as $kadmin){
                                            $admin_condition = [];
                                            $admin_condition [] = ['id','=',$kadmin];
                                            $admin_data = WaAdmins::find($admin_condition);
                                            $admin_data = json_decode($admin_data);
                                            $data = [
                                                'mobile' => $admin_data->mobile,
                                                'title' => '销售订单审批', // 标题
                                                'markdown' => '有一条销售订单'. $approves->sales_order_sn . '需要(轮到)你帮忙审批/'.$time, // 内容
                                            ];
                                            $currentRoute  = $request->host();
                                            // 消息通知
                                            if ( $currentRoute == 'frontforeign.olivenev.com'){
                                                $message =  MessageNotifyController::dingDingWorkNotify($data, $adminId);
                                            }
                                        }

                                    }


                                }

                            }

                        } else {
                            return IndexController::errored('', '不满足操作条件,请查看合同审批状态 和 审批权限');
                        }
//                    }
                    }
                }

            }
            elseif ($param['status'] == 2) {


                // 审批驳回 修改：销售订单状态为 审批驳回 添加审批驳回的理由两边都要 添加销售订单审批详情记录
                // 审批驳回驳回后是创建新的审批流  旧的失败记录保留
                // 手动创建的销售订单
                $up_purchase_approve_status = WaSalesOrdersExamineApprove::updated(['id' => $param['id']], ['status' => 2, 'refuse_reason' => $param['refuse_reason'], 'updated_at' => dateTime()]); // 修改销售订单审批单状态
                // 添加销售订单审批详情记录
                $approve_log_data = [
                    'sale_no' => $approves->sale_no, // 销售订单编号
                    'check_id' => $approves->id, // 审批id
                    'created_at' => dateTime(),
                    'admin_id' => $adminId->id,
//                'admin_ids' => json_encode($flow[0]->approve_flow), //
//                    'admin_ids' => json_encode($flow->approve_admin_id), //
                    'admin_name' => $adminId->nickname,
                    'refuse_reason' => $refuse_reason,
                    'status' => 2, //0 待审批 1审批通过 2 审批驳回 3作废 4  删除
                ];
                if ($approves->sales_order_sn) {
                    $approve_log_data['sales_order_sn'] = $approves->sales_order_sn;// 销售订单编号
                }
                $approve_log_data['refuse_reason'] = $param['refuse_reason'];
                $add_log = WaSalesOrdersExamineApproveFlow::create($approve_log_data); // 添加销售订单审批详情记录
                if (!$add_log) {
                    return IndexController::errored('', '审批流日志添加失败');
                }
                //销售订单状态
                PublicCommentController::销售订单状态;
                $purchase_orders_status = WaOrders::updated(['status' => 18,'refuse_reason' => $param['refuse_reason'], 'updated_at' => dateTime()], ['order_sn' => $approves->sales_order_sn]); // 审批驳回
                $purchase_orders_status = json_decode($purchase_orders_status);
                if (!$purchase_orders_status) {
                    return IndexController::errored('', '销售订单状态修改失败');
                }
            }
            elseif ($param['status'] == 3) {
                // 撤回 -> 整个合同和审批都撤回 并添加操作记录
                return IndexController::errored('', '撤回是销售订单页面操作,这边是审批只添加撤回记录，不做实际操作');
            } else {
                return IndexController::errored('', '销售订单审批状态没有此状态');
            }

            \support\Db::commit();
            return IndexController::successed('', '销售订单审批状态修改成功');
        } catch (\Throwable $exception) {
            IndexController::logError('salesOrdersApproveUpdate', $param, $adminId, $exception);

            \support\Db::rollBack();
            return IndexController::errored($exception, '销售订单审批状态修改失败');
        }

    }

    /**
     * 销售订单审批-详情
     * @param Request $request
     * @return \support\Response
     */
    public function salesOrdersApproveDetail(Request $request)
    {

//        process($request);
        $param = $request->all();
        $adminId = json_decode(adminId($request));
        $sales_approve = WaSalesOrdersExamineApprove::find([
            ['sales_order_sn', '=', $param['sales_order_sn']],
            ['status', '!=', 3],
            ['sale_no', '=', $param['sale_no']]

        ],
            $adminId);
        $sales_approve = json_decode($sales_approve);
        // 获取审批数据 审批
        if ($sales_approve) {
            $sales_approve->approve_flow = json_decode($sales_approve->approve_flow);
            foreach ($sales_approve->approve_flow as $kapprove) {
                $admin_name ='';
                if ($kapprove->approve_admin_id){
                    foreach ($kapprove->approve_admin_id as $apadid) {
                        $admins = WaAdmins::find(['id' => $apadid]);
                        $admins = json_decode($admins);
                        if ($admins) {
                            $department = WaDepartment::find(['id' => $admins->department_id]);
                            $department = json_decode($department);
                            if ($department){
                                $admin_name = $admin_name .'/'. $admins->nickname .'('. $department->name .')';

                            }else{
                                $admin_name = $admin_name .'/'. $admins->nickname;

                            }
                        }
                    }

                }



                $kapprove->check_time = '';
                $kapprove->refuse_reason = '';
                $kapprove->status = 0;
                $kapprove->status_name = '待审批';
                $kapprove->admin_name = $admin_name;
//                $kapprove->department_name = $department->name;
            }

            if ($sales_approve->initiator_admin_id){
                $admins = WaAdmins::find(['id' => $sales_approve->initiator_admin_id]);
                $admins = json_decode($admins);
                if ($admins) {
                    $department = WaDepartment::find(['id' => $admins->department_id]);
                    $department = json_decode($department);
                    if ($department){
                        $sales_approve->initiator_admin_name = $sales_approve->initiator_admin_name .'('. $department->name .')';
                    }
                }
            }

            // 销售单审批状态  0 待审核 1 审批通过 2 审批驳回  3 作废 4  删除
            if ($sales_approve->status == 0) {
                $sales_approve->status_name = '待审核';
            } elseif ($sales_approve->status == 1) {
                $sales_approve->status_name = '审批通过';
            } elseif ($sales_approve->status == 2) {
                $sales_approve->status_name = '审批驳回';
            } elseif ($sales_approve->status == 3) {
                $sales_approve->status_name = '已撤回';
            } elseif ($sales_approve->status == 4) {
                $sales_approve->status_name = '删除';
            } else {
                $sales_approve->status_name = '';
            }
            // 审批进度
            if ($sales_approve->id) {

//                $sales_approve_flow = WaSalesOrdersExamineApproveFlow::all(['check_id' => $sales_approve->id]);
                $sales_approve_flow = WaSalesOrdersExamineApproveFlow::all(['sale_no' => $sales_approve->sale_no]);
                $sales_approve_flow = json_decode($sales_approve_flow);
                if ($sales_approve_flow) {
                    foreach ($sales_approve_flow as $approve) {
                        // 状态
                        if (intval($approve->status) == 0) {
                            $approve->status_name = '审批中';
                        } elseif ($approve->status == 1) {
                            $approve->status_name = '审批通过';

                            if ($sales_approve->approve_flow) {
                                foreach ($sales_approve->approve_flow as $kapprove) {
                                    if (in_array($approve->admin_id,$kapprove->approve_admin_id)   && $approve->status == 1){
                                        $kapprove->admin_name = $approve->admin_name;
                                        $kapprove->check_time = $approve->updated_at;
                                        $kapprove->refuse_reason = $approve->refuse_reason;
                                        $kapprove->status = $approve->status;
                                        $kapprove->status_name = $approve->status_name;
//                                        $kapprove->department_id = $approve->department_id;
//                                        $kapprove->department_name = $approve->department_name;

                                    }
                                }
                            }

                        } elseif ($approve->status == 2) {
                            $approve->status_name = '审批驳回';

                            if ($sales_approve->approve_flow) {
                                foreach ($sales_approve->approve_flow as $kapprove) {
                                    if (in_array($approve->admin_id,$kapprove->approve_admin_id)  && $approve->status == 2){
                                        $kapprove->admin_name = $approve->admin_name;
                                        $kapprove->check_time = $approve->created_at;
                                        $kapprove->refuse_reason = $approve->refuse_reason;
                                        $kapprove->status = $approve->status;
                                        $kapprove->status_name = $approve->status_name;
//                                        $kapprove->department_id = $approve->department_id;
//                                        $kapprove->department_name = $approve->department_name;

                                    }
                                }
                            }

                        } elseif ($approve->status == 3) {
                            $approve->status_name = '已撤回';

                            if ($sales_approve->approve_flow) {
                                foreach ($sales_approve->approve_flow as $kapprove) {
                                    if (in_array($approve->admin_id,$kapprove->approve_admin_id)  && $approve->status == 3){
                                        $kapprove->admin_name = $approve->admin_name;
                                        $kapprove->check_time = $approve->created_at;
                                        $kapprove->refuse_reason = $approve->refuse_reason;
                                        $kapprove->status = $approve->status;
                                        $kapprove->status_name = $approve->status_name;
//                                        $kapprove->department_id = $approve->department_id;
//                                        $kapprove->department_name = $approve->department_name;

                                    }
                                }
                            }
                        } else {
                            $approve->status_name = '';
                        }



                    }

                    $sales_approve->initiator = $sales_approve_flow[0];
                }
                $sales_approve->purchase_approve_flow = $sales_approve_flow;
            } else {
                $sales_approve->purchase_approve_flow = [];
                $sales_approve->initiator = '';
            }

        } else {
            return IndexController::errored('', '获取销售审批数据失败');
        }

        return IndexController::successed(json_encode($sales_approve), '');
    }

}